import React, {Component} from 'react';
import PropTypes from 'prop-types';


// export default class App extends Component {
export default class Counter extends Component {
    static propTypes = {
        count: PropTypes.number.isRequired,
        increment: PropTypes.func.isRequired,
        decrement: PropTypes.func.isRequired
    }
    // 使用箭头函数保证 this 是组件对象
    increment = () => {
        // 获取selection选中的值
        const value = this.select.value * 1;

        // 调用store 的方法更新转态
        // this.props.store.dispatch(actions.increment(value))
        this.props.increment(value);
    }
    decrement = () => {
        // 获取selection选中的值
        const value = this.select.value * 1;

        // 调用store 的方法更新转态
        // this.props.store.dispatch(actions.decrement(value));
        this.props.decrement(value);

    };
    incrementIfOdd = () => {


        // 获取selection选中的值
        const value = this.select.value * 1;

        // 获取当前值
        // let count = this.props.store.getState();
        let count = this.props.count;

        // 判断满足状态才更新
        if (count % 2 === 1) {

            // 更新转态
            // this.props.store.dispatch(actions.increment(value))
            this.props.increment(value);
        }


    }
    incrementAsync = () => {

        // 获取selection选中的值
        const value = this.select.value * 1;

        // 启动延时定时器
        setTimeout(() => {
            // 更新转态
            // this.props.store.dispatch(actions.increment(value))
            this.props.increment(value);
        }, 1000)

    }

    render() {
        // const {count} = this.state
        const {count} = this.props;
        console.log("render()....", count)

        return (
            <div>
                <p>click {count} times</p>
                <div>
                    <select ref={(input) => this.select = input}>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                    </select>&nbsp;
                    <button onClick={this.increment}>+</button>
                    &nbsp;
                    <button onClick={this.decrement}>-</button>
                    &nbsp;
                    <button onClick={this.incrementIfOdd}>increment if odd</button>
                    &nbsp;
                    <button onClick={this.incrementAsync}>increment async</button>
                </div>
            </div>
        );
    }
};

